<template>
  <div class="column_container">
    <div class="bottom_l">
      <vxe-toolbar>
        <template #buttons>
          <el-row :gutter="20">
            <el-col :span="1.5" v-if="false">
              <vxe-radio-button
                v-model="selectAllLeft"
                :label="true"
                :content="!selectAllLeft ? '全选' : '取消全选'"
                :strict="false"
                size="mini"
                class="b-border"
              ></vxe-radio-button>
            </el-col>
            <el-col :span="4.5">
              <vxe-button
                @click="handleSubmitSaveAll"
                size="mini"
                v-hasPermi="['system:privileg:save']"
                >保存整站（每次仅限一个）</vxe-button
              >
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>

      <vxe-table
        highlight-current-row
        highlight-hover-row
        row-key
        row-id="siteId"
        show-overflow
        ref="xTreeLeft"
        border="inner"
        :data="leftList"
        :tree-config="{
          children: 'children',
          transform: false,
          parentKey: 'parentId',
          line: true,
          iconOpen: 'el-icon-remove',
          iconClose: 'el-icon-circle-plus',
        }"
        :checkbox-config="{
          labelField: 'name',
          showHeader: false,
          checkStrictly: false,
          checkRowKeys: checkRowKeys1,
          checkMethod,
          trigger: 'default',
        }"
        class="left-table"
        @current-change="haldleClickSite"
      >
        <vxe-column tree-node title="可选站点列表" show-overflow>
          <!-- <vxe-column type="checkbox" tree-node title="可选站点列表" show-overflow> -->
          <template #default="{ row }" class="aaaa">
            <span>
              <img
                src="../../../../assets/icons/png/globe.gif"
                alt=""
                style="vertical-align: bottom"
              />
              <span style="cursor: pointer; fontsize: 12px; color: #000">
                {{ row.name }}</span
              >

              <span class="channelId">{{ row.channelId || row.siteId }} </span>
              <span
                v-if="
                  (row.channelId || row.siteId || row.net) == currentRowId &&
                  !row.root
                "
                class="activeRow-right"
              >
                <svg-icon icon-class="left" style="color: #009a94" />
              </span>
            </span>
          </template>
        </vxe-column>
      </vxe-table>
    </div>
    <div class="bottom_r">
      <vxe-toolbar>
        <template #buttons>
          <el-row :gutter="20">
            <el-col :span="1.5">
              <vxe-radio-button
                v-model="expend"
                :label="true"
                v-if="false"
                :content="expend ? '全部关闭' : '全部展开'"
                :strict="false"
                size="mini"
                :disabled="!siteRow"
                class="b-border"
              ></vxe-radio-button>
            </el-col>

            <el-col :span="1.5">
              <!-- <vxe-button @click="haldleClickSelectAll" size="mini">全选</vxe-button> -->
              <vxe-radio-button
                v-model="selectAll"
                :label="true"
                :content="!selectAll ? '全选' : '取消全选'"
                :strict="false"
                size="mini"
                :disabled="!siteRow"
                class="b-border"
              ></vxe-radio-button>
            </el-col>
            <el-col :span="4.5">
              <vxe-button
                @click="handleSubmitSaveOne"
                size="mini"
                v-hasPermi="['system:privileg:save']"
                >保存栏目</vxe-button
              >
            </el-col>

            <el-col :span="1.5">
              <vxe-checkbox
                v-model="menuCheckStrictly"
                content="父子联动"
              ></vxe-checkbox>
            </el-col>
          </el-row>
        </template>
      </vxe-toolbar>

      <vxe-table
        highlight-current-row
        highlight-hover-row
        row-key
        row-id="channelId"
        show-overflow
        ref="xTreeRight"
        border="inner"
        :data="rightList"
        :tree-config="{
          children: 'children',
          transform: false,
          parentKey: 'parentId',
          line: true,
          iconOpen: 'el-icon-remove',
          iconClose: 'el-icon-circle-plus',
        }"
        :checkbox-config="{
          labelField: 'name',
          showHeader: false,
          checkStrictly: !menuCheckStrictly,
          checkRowKeys: checkRowKeys2,
          checkMethod,
          trigger: 'default',
        }"
        class="left-table"
        v-if="siteRow"
      >
        <!-- 要用rightList.length判断。不能使用siterow -->
        <vxe-column type="checkbox" tree-node show-overflow>
          <template #title="{ row }">
            <span>
              <span style="cursor: pointer; fontsize: 12px; color: #000"
                >{{ siteRow.name }} 下的栏目列表
              </span>
              <span style="float: right; margin: 0 10px 0 0"
                >已选择
                {{ $refs.xTreeRight.getCheckboxRecords().length }} 个栏目</span
              >
            </span>
          </template>
          <template #default="{ row }">
            <span>
              <span style="cursor: pointer; fontsize: 12px; color: #000">
                {{ row.name }}</span
              >
              <span class="channelId">{{ row.channelId || row.siteId }} </span>
            </span>
          </template>
        </vxe-column>
      </vxe-table>
      <div
        class="vxe-loading is--visible vxe-table--loading"
        v-else-if="loading"
      >
        <div class="vxe-loading--chunk">
          <i class="vxe-icon-spinner roll vxe-loading--default-icon"></i>
          <div class="vxe-loading--text">加载中...</div>
        </div>
      </div>
      <font color="red" v-else>请先选择站点</font>
    </div>
  </div>
</template>

<script>
import { listSite } from "@/api/content/net";
import { getChannelListForTree } from "@/api/content/clounm";
import {
  savePrivilegeConfig, //部分栏目  或者站点
  autoPrivlige, //整个站点保存
  getSlecteChannelList,
} from "@/api/system/userGroup";

import { mapState } from "vuex";
import { Aside } from "element-ui";
export default {
  props: {
    WebSite: {},
    Channel: {},
  },

  data() {
    return {
      //全部展开 全部关闭
      expend: false,
      //全选。全不选
      selectAll: false,
      selectAllLeft: false,
      //是否父子联动
      menuCheckStrictly: false,
      // 右侧栏目列表 loading
      loading: false,
      //站点列表
      leftList: [],
      //栏目列表
      rightList: [],
      // 选中的栏目id  已jion（’）
      cloumnIds: "",
      siteIds: "",
      //栏目默认选中
      checkRowKeys1: [],
      checkRowKeys2: [],
      siteRow: {},
      columnRow: {},
      //外部的站点行。
      outSiteRow: JSON.parse(sessionStorage.getItem("setSiteRow")),
      //外部的用户组行
      outGroupRow: JSON.parse(sessionStorage.getItem("userGroupRow")),

      rightAllChannelId: [], // 右侧 当前站点对应的  所有的栏目id
    };
  },

  components: {},

  computed: {
    ...mapState(["column"]),
    currentRowId() {
      return this.siteRow?.siteId;
    },
  },
  created() {
    this.checkRowKeysSiteIds();
    //siteid==1  是平台系统。要获取所有的站点。
    this.outSiteRow.siteId == this.CONSTANCE.siteId
      ? this.getSiteList()
      : this.getSiteList2();
  },
  mounted() {},

  watch: {
    expend(value) {
      if (value) {
        this.$refs.xTreeRight.setAllTreeExpand(true);
      } else {
        this.$refs.xTreeRight.clearTreeExpand();
        // this.$nextTick(() => {
        //   this.$refs.xTreeRight.setTreeExpand(this.rightList[0], true);
        // });
      }
    },
    selectAll(value) {
      if (value) {
        this.menuCheckStrictly = true;
        this.$nextTick(() => {
          this.$refs.xTreeRight &&
            this.$refs.xTreeRight.setAllCheckboxRow(true);
        });
      } else {
        this.$refs.xTreeRight && this.$refs.xTreeRight.setAllCheckboxRow(false);
        this.$nextTick(() => {
          this.menuCheckStrictly = false;
        });
      }
    },
    selectAllLeft(value) {
      this.$refs.xTreeLeft.setAllCheckboxRow(value ? true : false);
    },
  },

  methods: {
    //获取站点列表
    getSiteList() {
      this.siteRow = undefined;
      this.columnRow = undefined;
      listSite().then((res) => {
        // this.leftList = [
        //   { name: "WYCMS主站", root: "000", children: res.data },
        // ];
        this.leftList = res.data;
      });
      // .then(() => {
      //   //展开第一个节点
      //   this.$nextTick(() => {
      //     this.$refs.xTreeLeft.setTreeExpand(this.leftList[0], true);
      //   });
      // });
    },
    //不是平台系统只显示当前站点
    getSiteList2() {
      this.siteRow = undefined;
      this.columnRow = undefined;
      this.leftList = [this.outSiteRow];
    },
    //点击站点行  获取栏目列表
    async haldleClickSite({ row }) {
      console.log("row: ", row);
      this.expend = false;
      this.selectAll = false;
      this.siteRow = undefined;

      this.loading = true;

      if (row.root || row.siteId == this.siteRow?.siteId) return;
      //重置右侧表格。可以默认选中   或者重置siteRow
      this.rightList = [];
      //高亮当前行
      this.$refs.xTreeLeft.setCurrentRow(row);
      await this.handleGetSlectChannelList({
        siteId: row.siteId,
        groupId: this.column.userGroupRow.groupId,
      });
      getChannelListForTree({ siteId: row.siteId })
        .then(async (res) => {
          this.siteRow = row;
          this.rightAllChannelId = res.data.map((item) => {
            return item.channelId;
          });
          console.log(" this.rightAllChannelId: ", this.rightAllChannelId);

          // 自己循环获取已选中id'
          // this.checkRowKeysColumns();
          //接口获取已选择id

          // let obj = JSON.parse(JSON.stringify(this.siteRow));
          // obj.children = this.handleTree(res.data, "channelId").filter((item)=>item.parentId ==row.siteId);
          // obj.root = "111";
          this.rightList = this.handleTree(res.data, "channelId").filter(
            (item) => item.parentId == row.siteId
          );
          console.log("this.rightList: ", this.rightList);
          this.$nextTick(() => {
            this.loading = false;
            console.log(" this.loading: ", this.loading);
          });
        })
        .then(() => {
          //展开第一个节点
          // this.$nextTick(() => {
          //   this.$refs.xTreeRight.setTreeExpand(this.rightList[0], true);
          // });
        });
    },
    //单独保存
    handleSubmitSaveOne() {
      if (!this.$refs.xTreeRight) {
        this.msgError("请选择站点，栏目");
        return;
      }
      let checkRowkey = this.checkRowKeys2;
      let arr = [];

      //先获取到非本栏目的id   再concat本栏目选中的id
      checkRowkey.forEach((item) => {
        if (this.rightAllChannelId.indexOf(item) == -1 && item != 0) {
          arr.push(item);
        }
      });
      console.log("去掉本栏目的其他栏目id", arr);
      let selectionId = this.$refs.xTreeRight
        .getCheckboxRecords()
        .map((item) => item.channelId);
      console.log("当前已选中的行数据selectionId: ", selectionId);

      let selectionId2 = this.$refs.xTreeRight
        .getCheckboxIndeterminateRecords(true)
        .map((item) => item.channelId);
      console.log(
        "this.$refs.xTreeRight.getCheckboxIndeterminateRecords()",
        this.$refs.xTreeRight.getCheckboxIndeterminateRecords(true)
      );
      console.log(
        "this.$refs.xTreeRight.getCheckboxRecords()",
        this.$refs.xTreeRight.getCheckboxRecords()
      );

      let name = this.$refs.xTreeRight.getCheckboxRecords().map((item) => {
        console.log("item: ", item);
        return item.name;
      });
      console.log("选中的栏目名称", name);
      // if (selectionId.length == 0) {
      //   this.msgError("请选择栏目");
      //   return;
      // }
      this.cloumnIds =
        this.outSiteRow.siteId == 1
          ? [...new Set(selectionId.concat(selectionId2).concat(arr))].join(",") //平台系统
          : [...new Set(selectionId.concat(selectionId2))].join(",");
      console.log("该用户组所选的全部栏目id", this.cloumnIds);
      Promise.all([
        new Promise((resolve) => {
          savePrivilegeConfig({
            functionIdStr: this.cloumnIds || 0,
            groupId: this.column.userGroupRow.groupId,
            type: "Channel",
          }).then((res) => {
            resolve(res);
          });
        }),
        new Promise((resolve) => {
          let webSiteIds = this.WebSite.map((item) => {
            return item.functionId;
          });
          console.log(
            "🚀 ~ file: Three.vue ~ line 281 ~ webSiteIds ~ webSiteIds",
            webSiteIds
          );
          if (!webSiteIds.includes(this.siteRow.siteId))
            webSiteIds.push(this.siteRow.siteId);

          savePrivilegeConfig({
            functionIdStr:
              this.cloumnIds.length > 0 ? webSiteIds.join(",") : -1,
            groupId: this.column.userGroupRow.groupId,
            type: "WebSite",
          }).then((res) => {
            resolve(res);
          });
        }),
      ]).then((res) => {
        this.$emit("getGroupInitPrivilege");
        this.msgSuccess("保存成功");
      });
    },
    //保存整站   03、将选择的网站的所有栏目赋予当前用户组
    handleSubmitSaveAll() {
      if (!this.siteRow) {
        this.msgError("请选择站点");
        return;
      }
      this.$confirm(
        "是否确认将 “ " + this.siteRow.name + " ” 的所有栏目赋予当前用户组?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(() => {
          autoPrivlige({
            siteId: this.siteRow.siteId,
            groupId: this.column.userGroupRow.groupId,
          }).then((res) => {
            if (res.code == 200) {
              this.msgSuccess("保存成功");
            }
          });
        })
        .catch(() => {});
    },
    //保存整站   02、保存用户组可见的站点、栏目、模板、菜单等权限配置
    // handleSubmitSaveAll() {
    //   let selectionId = this.$refs.xTreeLeft
    //     .getCheckboxRecords()
    //     .map((item) => item.siteId);

    //   this.templateIds =
    //     this.outSiteRow.siteId == 1
    //       ? [...new Set(selectionId)].join(",")
    //       : [...new Set(selectionId)].join(",");

    //   savePrivilegeConfig({
    //     functionIdStr: this.templateIds,
    //     groupId: this.column.userGroupRow.groupId,
    //     type: "WebSite",
    //   }).then((res) => {
    //     if (res.code == 200) {
    //       this.$emit("getGroupInitPrivilege");
    //       this.msgSuccess("保存成功");
    //     }
    //   });
    // },
    // 获取已选中的站点
    checkRowKeysSiteIds() {
      let checkedKeys = this.WebSite;
      let arr = [];
      checkedKeys.forEach((v) => {
        arr.push(v.functionId);
        return;
        this.$nextTick(() => {
          this.$refs.menu.setChecked(v.functionId, true, false);
        });
        setCheckboxRow;
      });
      this.checkRowKeys1 = arr;
    },
    //获取已选中的栏目
    async handleGetSlectChannelList(data) {
      this.checkRowKeys2 = [];
      await getSlecteChannelList(data).then((res) => {
        this.checkRowKeys2 = res.data;
        console.log(" this.checkRowKeys2: ", this.checkRowKeys2);
      });
    },
    //获取已选中的栏目
    checkRowKeysColumns() {
      return;
      let checkedKeys = this.Channel;
      let arr = [];
      this.checkRowKeys2 = [];
      checkedKeys.forEach((v, index) => {
        // if (this.rightAllChannelId.indexOf(v.functionId) > -1) {
        //   arr.push(v.functionId);
        // }
        if (this.rightAllChannelId.includes(v.functionId) > -1) {
          arr.push(v.functionId);
        }
        this.checkRowKeys2.push(v.functionId);
        return;

        this.$nextTick(() => {
          this.$refs.xTreeRight.setCheckboxRow(v.functionId, true, false);
        });
      });

      if (arr.length == this.rightAllChannelId.length) {
        this.selectAll = true;
      } else {
        this.selectAll = false;
      }
      // this.checkRowKeys2 = arr;
      console.log(" this.checkRowKeys2: ", this.checkRowKeys2);
    },
    haldleClickSelectAll() {
      this.menuCheckStrictly = true;
      this.$nextTick(() => {
        this.$refs.xTreeRight.setAllCheckboxRow(true);
      });
    },
    checkMethod({ row }) {
      return !row.root;
    },
  },
};
</script>

<style scoped lang="scss">
.column_container {
  height: 100%;
  display: flex;
  flex-direction: row;
}
.bottom_l {
  // overflow: auto;
  min-width: 300px;
  width: 300px;
  height: 100%;
  display: flex;
  flex-direction: column;
  .left-table {
    flex: 1;
    height: 0;
    overflow: overlay;
    overflow: auto;
  }
}
.bottom_r {
  flex: 1;
  overflow: auto;
  padding: 0 0 0 30px;
  display: flex;
  flex-direction: column;
  .left-table {
    flex: 1;
    // height: 0;
    overflow: overlay;
    overflow: auto;
  }
}
// ::v-deep .body--wrapper {
//   background: transparent !important;
// }
// ::v-deep .vxe-toolbar {
//   background: transparent !important;
// }
.b-border ::v-deep .vxe-radio--label {
  border-radius: 4px 4px 4px 4px;
}
</style>
